package org.yoki.edu.portal.web.rest.portal.auth;

import com.yunzhitx.cloud.common.model.InvokeResult;
import com.yunzhitx.cloud.common.model.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.yoki.edu.common.protocol.portal.msg.PortalV1Msg;
import org.yoki.edu.common.protocol.portal.v1.sender.PortalV1PapMsgSender;
import org.yoki.edu.portal.core.exception.BasicRestStatus;
import org.yoki.edu.portal.core.portal.vo.MobileAuthReqVo;
import org.yoki.edu.portal.core.radius.domain.Radcheck;
import org.yoki.edu.portal.web.utils.CommonUtils;
import org.yoki.edu.portal.web.utils.PhoneCodeUtils;
import org.yoki.edu.portal.web.utils.SmsHttp;

/**
 * Created by kissy on 2017/3/2.
 */
@RestController
@RequestMapping("portal/auth/phone")
public class PortalPhoneAuthRest {
    private static Logger logger = LoggerFactory.getLogger(PortalPhoneAuthRest.class);

    @Autowired
    private SmsHttp smsHttp;

    @Value("${portal.base.url}")
    private String baseUrl;

    @Value("${portal.ac.ip}")
    private String acIp;
    @Value("${portal.ac.port}")
    private Integer acPort;

    @Value("${weixin.mp.appId}")
    private String appId;
    @Value("${weixin.mp.shopId}")
    private String shopId;
    @Value("${weixin.mp.secretKey}")
    private String secretKey;

    /**
     * 获取认证密码
     *
     * @param cellphone
     * @return
     */
    @RequestMapping(value = "getPassword", method = RequestMethod.GET)
    public ResponseEntity<InvokeResult> getPassword(String cellphone) {
        if (CommonUtils.isEmpty(cellphone)) {
            throw new BizException(BasicRestStatus.paramPhoneFormatErrorStatus);
        }
        InvokeResult invokeResult;
        try {
            String code = PhoneCodeUtils.getCode(6);
            Radcheck radcheck = new Radcheck();
            radcheck.setUsername(cellphone);
            radcheck.setValue(code);
            radcheck.setLoginType("phone");
            radcheck.saveOrUpdatePwd();
            //发送短信验证码
            smsHttp.sendMsg(cellphone, code);
            invokeResult = InvokeResult.ok();
            invokeResult.setMsg("手机号码已经下发至您的手机，请注意查收！");
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.OK);
    }

    /**
     * 用户认证
     *
     * @param vo
     * @return
     */
    @RequestMapping(value = "userAuth", method = RequestMethod.POST)
    public InvokeResult userAuth(MobileAuthReqVo vo) {
        InvokeResult invokeResult = null;
        if (null == vo || CommonUtils.isEmpty(vo.getLoginname(), vo.getPassword())) {
            invokeResult = InvokeResult.failure("请填写手机号和验证码！");
        } else if (!CommonUtils.isChinaPhoneLegal(vo.getLoginname())) {
            invokeResult = InvokeResult.failure("手机号格式有误！");
        } else {
            //用户登陆IP
            String loginIp = vo.getUserpriip();
            int serialNo = (int) (65535 * Math.random());
            PortalV1PapMsgSender sender = new PortalV1PapMsgSender();
            sender.setTimeOut(60000);
            try {
                PortalV1Msg reciveMsg = sender.sendAndParseReqAuth(serialNo, loginIp, vo.getLoginname(), vo.getPassword(), acIp, acPort);
                sender.sendAffAckAuth(serialNo, loginIp, acIp, acPort);
                //重置密码，防止密码可以多次使用
                Radcheck radcheck = new Radcheck() ;
                radcheck.setUsername(vo.getLoginname());
                radcheck.setLoginIp(loginIp);
                radcheck.setDeviceMac(vo.getDeviceMac());
                radcheck.updateIpAndMac();
                invokeResult = InvokeResult.ok();
            } catch (BizException e) {
                e.printStackTrace();
                invokeResult = InvokeResult.failure(e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                invokeResult = InvokeResult.error();
            }

        }
        return invokeResult;
    }




}
